from typing import Optional
from fastapi import APIRouter, HTTPException, Path, Query
from app.crud.honor import honor_crud
from app.schemas.honor import (
    HonorCreate,
    HonorUpdate,
    HonorResponse,
    HonorListResponse,
    HonorDetailResponse
)
from app.models.models import HonorType

router = APIRouter(prefix="", tags=["荣誉管理"])

@router.post("/", response_model=HonorResponse, summary="创建荣誉")
async def create_honor(honor_data: HonorCreate):
    """创建荣誉"""
    try:
        honor = await honor_crud.create(honor_data)
        return HonorResponse.model_validate(honor)
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"创建荣誉失败: {str(e)}")

@router.get("/", response_model=HonorListResponse, summary="获取荣誉列表")
async def get_honors(
    skip: int = Query(0, ge=0, description="跳过记录数"),
    limit: int = Query(20, ge=1, le=100, description="每页记录数"),
    search: Optional[str] = Query(None, description="搜索关键词（荣誉名称/学员姓名）"),
    student_id: Optional[int] = Query(None, description="学员ID"),
    type: Optional[HonorType] = Query(None, description="荣誉类型")
):
    honors, total = await honor_crud.get_list(
        skip=skip,
        limit=limit,
        search=search,
        student_id=student_id,
        type=type
    )
    honor_responses = [HonorResponse.model_validate(honor) for honor in honors]
    return HonorListResponse(total=total, items=honor_responses)

@router.get("/{honor_id}", response_model=HonorDetailResponse, summary="获取荣誉详情")
async def get_honor(honor_id: int = Path(..., description="荣誉ID")):
    honor = await honor_crud.get_by_id(honor_id)
    if not honor:
        raise HTTPException(status_code=404, detail="荣誉不存在")
    return HonorDetailResponse.model_validate(honor)

@router.put("/{honor_id}", response_model=HonorResponse, summary="更新荣誉信息")
async def update_honor(
    honor_id: int = Path(..., description="荣誉ID"),
    honor_data: HonorUpdate = None
):
    existing = await honor_crud.get_by_id(honor_id)
    if not existing:
        raise HTTPException(status_code=404, detail="荣誉不存在")

    updated = await honor_crud.update(honor_id, honor_data)
    if not updated:
        raise HTTPException(status_code=400, detail="更新失败")

    return HonorResponse.model_validate(updated)

@router.delete("/{honor_id}", summary="删除荣誉")
async def delete_honor(honor_id: int = Path(..., description="荣誉ID")):
    success = await honor_crud.delete(honor_id)
    if not success:
        raise HTTPException(status_code=404, detail="荣誉不存在")
    return {"message": "荣誉删除成功"}